import {PageContainer} from "@ant-design/pro-layout";
import type {ActionType, ProColumns} from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import {StatusEnum, MenuIconEnum} from "@/services/abis/enum";
import {addMenu, deleteMenuById, editMenuById, getMenus, getMenuTree} from "@/services/abis/menu";
import type { ProFormInstance} from "@ant-design/pro-form";
import {ModalForm, ProFormDigit, ProFormGroup, ProFormSelect, ProFormText} from "@ant-design/pro-form";
import {useRef, useState} from "react";
import {Button, Form, Input, message, Space, TreeSelect} from "antd";

/**
 * 树形菜单节点
 */
type treeNode = {
  title: string;
  value: number;
  children?: treeNode[]
}

/**
 * 将菜单树转换成指定的 treeNode 格式
 * @param menuTree
 */
const generateMenuTree = (menuTree: ABIS.MenuTree[]): treeNode[] => (
  menuTree.map(({id, name, children}) => {
    return {
      title: name,
      value: id,
      children: children && generateMenuTree(children)
    }
  })
)

export default () => {
  const [modalVisit, setModalVisit] = useState(false)
  const [treeData, setTreeData] = useState<treeNode[]>([])
  const [isEdit, setIsEdit] = useState<boolean>(false)
  const ref = useRef<ActionType>()
  const formRef = useRef<ProFormInstance>()

  /**
   * 删除菜单
   * @param ids
   */
  const deleteMenu = async (ids: number[]) => {
    const {data: result} = await deleteMenuById(ids)
    if (result) message.success('删除数据成功', 3)
    else message.error('删除失败', 3)
    ref.current?.reload()
  }

  /**
   * 编辑菜单信息
   * @param record
   */
  const editMenu = (record: ABIS.MenuVO) => {
    if (record.parent_id === 0) {
      delete record.parent_id
    }
    if (record.icon === '') {
      delete record.icon
    }
    setModalVisit(true)
    setIsEdit(true)
    formRef.current?.setFieldsValue(record)
  }

  /**
   * 表格列定义
   */
  const columns: ProColumns<ABIS.MenuVO>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      search: false
    },
    {
      title: '菜单',
      dataIndex: 'path'
    },
    {
      title: '菜单名称',
      dataIndex: 'name'
    },
    {
      title: '图标',
      dataIndex: 'icon',
      search: false,
      render: (_, record) => (
        record.icon && MenuIconEnum[record.icon]
      )
    },
    {
      title: '上级菜单',
      dataIndex: 'parent_name'
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: StatusEnum
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      render: (_, record) => {
        return record.created_at.replace('T', ' ')
      }
    },
    {
      title: '创建人',
      dataIndex: 'created_by_name',
      render: (_, record) => {
        return record.created_by === 0 ? '系统' : record.created_by_name
      }
    },
    {
      title: '最后更新时间',
      dataIndex: 'updated_at',
      search: false,
      render: (_, record) => {
        return record.updated_at ? record.updated_at.replace('T', ' ') : '-'
      }
    },
    {
      title: '最后更新人',
      dataIndex: 'updated_by_name'
    },
    {
      title: '操作',
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => {
            editMenu(record)
          }}>编辑</Button>
          <Button type="link" danger onClick={ async () => {
            await deleteMenu([record.id])
          }}>删除</Button>
        </Space>
      )
    }
  ]

  return (
    <>
      <PageContainer>
        <ProTable
          actionRef={ref}
          columns={columns}
          rowSelection={{}}
          rowKey={record => (record.id)}
          request={ async (params) => {
            const {data: menus} = await getMenus(params.current, params.pageSize)
            return {
              data: menus.list,
              success: true,
              total: menus.total
            }
          }}
          toolbar={{
            actions: [
              <Button type="primary" onClick={() => {
                setModalVisit(true)
                setIsEdit(false)
              }}>新建菜单</Button>,
              <ModalForm<ABIS.Menu | ABIS.MenuVO>
                title={isEdit ? '编辑菜单' : '新建菜单'}
                formRef={formRef}
                visible={modalVisit}
                onVisibleChange={ async (visible) => {
                  setModalVisit(visible)
                  if(!visible) {
                    formRef.current?.resetFields()
                  } else {
                    if (treeData.length == 0) {
                      const { data: menuTree } = await getMenuTree()
                      const generate = generateMenuTree(menuTree)
                      setTreeData(generate)
                    }
                  }
                }}
                modalProps={{
                  okText: isEdit ? '修改' : '新建'
                }}
                onFinish={ async (formData) => {
                  if (isEdit) {  // 编辑
                    const result = await editMenuById(formData.id, formData.name, formData.path,
                      formData.icon, formData.parent_id, formData.weight)
                    if (result.code === 1000) {
                      message.success('编辑菜单完成')
                    } else {
                      message.warn(result.message)
                    }
                  } else {  // 新增
                    const result = await addMenu(formData.name, formData.path, formData.icon,
                      formData.parent_id, formData.weight)
                    if (result.code === 1000 ) message.success('新建菜单完成')
                    else message.warn(result.message)
                  }
                  setModalVisit(false)
                  ref.current?.reload()
                }}
              >
                <ProFormGroup>
                  <ProFormText label="菜单名称" width="md"
                               name="name" required rules={[{ required: true, message: '菜单名称必须填写' }]}/>
                  <ProFormText label="菜单路径" width="md"
                               name="path" required rules={[{ required: true, message: '菜单路径必须填写' }]}/>
                  <Form.Item name="id">
                    <Input hidden />
                  </Form.Item>
                </ProFormGroup>
                <ProFormGroup>
                  <ProFormSelect valueEnum={MenuIconEnum} label="菜单图标" name="icon" width={"sm"}/>
                  <Form.Item label="上级菜单" name="parent_id">
                    <TreeSelect
                      allowClear
                      style={{width: '306px'}}
                      placeholder="请选择上级菜单"
                      treeData={treeData}
                    />
                  </Form.Item>
                  <ProFormDigit label="菜单排序" name="weight" min={1} max={9999} fieldProps={{precision: 0}} width="xs" />
                </ProFormGroup>
              </ModalForm>
            ]
          }}
          pagination={{hideOnSinglePage: true}}
        />
      </PageContainer>
    </>
  )
}
